<template>

	<view class="DetailView">
		<view class="content">
			<z-paging ref="paging" :refresher-only="true" :fixed="true" :show-loading-more-no-more-view='false'
				:refresher-enabled="false" :refresher-threshold="0" hide-refresher-when-reload
				hide-refresher-when-enabled>
				<template #top>
					<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" :isDock="true" :existTabBar="true"
						:initialBottom="160" @btnClick="scan">
						<template #BtnContent>
							<u-icon name="scan" color="#fff" size="54rpx"></u-icon>
						</template>
					</m-drag-button>
					<u-navbar :fixed="false" :title="WorkbenchesTitle+'详情'" :autoBack="true" :safeAreaInsetTop="true"
						leftIconColor="#fff" @leftClick='leftClick'></u-navbar>
				</template>

				<view class="MainBox">
					<u--form labelPosition="left" :model="baseFormData" :rules="rules" ref="uForm">

						<u-form-item labelWidth="100" label="单据号" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.BillNO" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="单据日期" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.BillDate" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" :label="WorkbenchesTitle +'人'" borderBottom
							:leftIconStyle="{'font-size':'20px'}" prop="EmplName" leftIcon="file-text">
							<u--input v-model="baseFormData.EmplName" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="领用时间" :leftIconStyle="{'font-size':'20px'}"
							v-if="WorkbenchesTitle=='领用'" leftIcon="calendar" @click="addTime('领用')">
							<u--input v-model="baseFormData.CKTime" placeholder="自动记录" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item labelWidth="100" label="归还时间" :leftIconStyle="{'font-size':'20px'}"
							v-if="WorkbenchesTitle=='归还'" leftIcon="calendar" @click="addTime('归还')">
							<u--input v-model="baseFormData.RKTime" placeholder="自动记录" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</u--form>
					<view class="AddBottomBox">
						<button class="CancelBtn" @click="openBaseScreen('模具','check')">查询</button>
					</view>
					<scroll-view scroll-x="true" class="scroll-view-fileList">
						<table class="fixed-table">
							<thead>
								<tr>
									<th class="sticky-col" width="50px">操作</th>
									<th width="100px">编号</th>
									<th width="100px">名称</th>
									<th width="100px">规格</th>
									<th width="100px">警告信息</th>
									<th width="130px">库位信息</th>

								</tr>
							</thead>
							<tbody>

								<tr v-for="(item, index) in tableData" :key="index"
									:class="{ 'text-red': item.WarningStatus != 0 }">
									<td class="sticky-col" width="50px">
										<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
									</td>
									<td width="100px">
										<view class="fixed-cell">
											<text>{{ item.MoludCode }}</text>
										</view>

									</td>
									<td width="100px">
										<view class="fixed-cell">
											<text>{{ item.MoludName }}</text>
										</view>

									</td>
									<td width="100px">
										<view class="fixed-cell">
											<text>{{ item.MoludSpec }}</text>
										</view>

									</td>
									<td width="100px">
										<view class="fixed-cell">
											<text>{{ item.WarningStatusName }}</text>
										</view>
									</td>
									<td width="130px">
										<view class="fixed-cell" @click="openBaseScreen('库位','radio',index)">
											<text>{{ item.FStorageName }}</text>
										</view>

									</td>

								</tr>
							</tbody>
						</table>
					</scroll-view>



				</view>
				<template #bottom>
					<view class="BottomBox safe_buttom" :style="$utils.disposeSafeBottomFun()">
						<button v-if="!baseFormData.Approve" class="CancelBtn" @click="SubmitBtn('保存')">提交</button>
						<button class="ComfirmBtn" @click="ToExamine('审核')"
							v-if='!baseFormData.Approve&&ApproveBack("审核")'>审核</button>

						<button class="ComfirmBtn" @click="ToExamine('取消审核')"
							v-if='baseFormData.Approve&&ApproveBack("取消审核")'>取消审核</button>
					</view>
				</template>
			</z-paging>

		</view>

		<u-modal :show="modalshow" :title="modaltitle" :content="modalcontent" :showCancelButton='true'
			@confirm='modalconfirm' @cancel='modalshow=false'>
		</u-modal>

		<u-toast ref="uToast"></u-toast>
		<u-datetime-picker :show="Timeshow" v-model="Timevalue" @cancel='Timeshow = false' mode="datetime"
			@confirm='pickerConfirm'></u-datetime-picker>
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>


	</view>

</template>

<script>
	import index from '../uni_modules/uview-ui';
	import {
		formatDateTime,
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/st_mold/common/base.js';
	import BaseMixin from '@/st_mold/common/base.js';
	export default {
		mixins: [BaseMixin],
		data() {
			return {
				rules: {
					'EmplName': {
						type: 'string',
						required: true,
						message: '保养领用人不能为空',
						trigger: ['change']
					}
				},
				baseFormData: {
					EmplName: '',
					EmplID: null,
					StockID: 0,
					BillDate: '',
					BillNO: null,
					RKTime: '',
					CKTime: '',
				},

				ButtonShow: true, //按钮显示
				BtnShow: false,

				loading: false, //是否加载中
				WorkbenchesTitle: '', //判断进来的是归还还是领用
				LYGHWSList: [], //警告列表
				tableData: [], //子表
				tableDataIndex: null, //子表索引
				TimeName: '', //时间名称
				Timeshow: false, //时间是否显示
				Timevalue: Number(new Date()), //时间值
				trashIndex: null, //删除索引
				modalshow: false, //模态框
				modaltitle: '提示', //模态框提示语
				modalcontent: '', //模态框提示语
				BtnApprove: [], //权限判断
				BaseScreenIndex: null, //选择库位的索引
			};
		},
		onLoad(item) {
			var that = this
			var MesBasicInfo = that.$store.state.CRaftModule.MesBasicInfo
			that.WorkbenchesTitle = MesBasicInfo.WorkbenchesTitle

			// 使用 Promise.all 确保所有数据加载完成
			// 先初始化数据
			that.initData()

			let foundNode = null;
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '模具管理') {
					for (const node of module.Node) {
						if (node.APFunName.includes(that.WorkbenchesTitle)) {

							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			console.log(foundNode);
			this.BtnApprove = foundNode['IconApprove'];
			console.log(this.BtnApprove);
			// 判断是否是扫码带出的对象
			var EquipmentObj
			if (item.EquipmentObj) {
				EquipmentObj = JSON.parse(item.EquipmentObj)
			}
			// 判断是否存在主表id
			if (item.StockID) {
				that.queryList(item.StockID)
			} else {
				// 判断是否有子表数组
				if (item.tableData) {
					var table = JSON.parse(item.tableData)
					if (table && table.length > 0) {
						that.tableData = table
					}
				}
				// 判断是否是扫码带出的对象
				if (EquipmentObj) {
					that.baseFormData.EquipmentName = that.baseFormData.EquipmentName ? that.baseFormData.EquipmentName :
						EquipmentObj.EquipmentName
					that.baseFormData.EquipmentID = that.baseFormData.EquipmentID ? that.baseFormData.EquipmentID :
						EquipmentObj.EquipmentID
				}
				// 人员显示
				that.baseFormData.EmplName = that.baseFormData.EmplName ? that.baseFormData.EmplName : that
					.$store.state.UserInfo.UserName
				// 人员id
				that.baseFormData.EmplID = that.baseFormData.EmplID ? that.baseFormData.EmplID : that.$store
					.state.UserInfo.EmplID
				// 单据日期
				that.baseFormData.BillDate = that.baseFormData.BillDate ? that.baseFormData.BillDate :
					getFormatDate(new Date())
				// 归还时间
				that.baseFormData.RKTime = that.baseFormData.RKTime ? that.baseFormData.RKTime :
					getFormatDate(new Date())
				// 领用时间
				that.baseFormData.CKTime = that.baseFormData.CKTime ? that.baseFormData.CKTime :
					getFormatDate(new Date())
			}
		},
		onUnload() {
			uni.$off('BatchEditScan');
			uni.$off('st_mold_Choice');
		},
		computed: {
			// 计算属性返回一个函数
			rowClass() {
				return (status) => ({
					'active-row-yellow': status != 0,

				});
			},
		},

		mounted() {
			var that = this;

			setTimeout(() => {
				that.BtnShow = true;
			}, 300)
			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})

			uni.$on('st_mold_Choice', function(ret) {
				console.log(ret);
				if (ret.type == '模具') {
					ret.data.map(item => {
						item.WarningStatus = item.WarningStatus ? item.WarningStatus : 0
						item.WarningStatusName = item.WarningStatusName ? item.WarningStatusName : ''
						item.StockDeID = item.StockDeID ? item.StockDeID : 0
					})
					that.tableData = [...that.tableData, ...ret.data]
				} else if (ret.type == '库位') {

					that.$set(that.tableData[that.BaseScreenIndex], 'FStorageName', ret.data.FStorageName);
					that.$set(that.tableData[that.BaseScreenIndex], 'FStorageID', ret.data.FStorageID);

				}
			});

		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {

		},
		methods: {

			async initData() {
				// 加载公共字典数据
				await this.loadCommonDictionaries([{
					type: 'LYGHWS',
					key: 'LYGHWSList'
				}]);
			},
			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				return Type;
			},
			// 子表删除
			trash(index) {
				var that = this
				that.trashIndex = index
				that.modaltitle = '提示'
				that.modalcontent = '是否删除第' + (index + 1) + '行'
				that.modalshow = true
				this.$forceUpdate()
			},
			// 提示框点击确认
			modalconfirm() {
				var that = this
				that.modalshow = false

				if (that.modaltitle == '提示') {
					that.tableData.splice(that.trashIndex, 1)
				}
			},
			// 获取到时间
			pickerConfirm(e) {
				var time = getFormatDate(new Date(e.value))
				if (this.TimeName == '领用') {
					this.baseFormData.CKTime = time
				} else {
					this.baseFormData.RKTime = time
				}
				this.Timeshow = false
			},
			// 打开时间筛选
			addTime(name) {
				this.TimeName = name
				if (this.TimeName == '领用') {
					this.Timevalue = Number(getTimeStamp(this.baseFormData.CKTime))
				} else {
					this.Timevalue = Number(getTimeStamp(this.baseFormData.RKTime))
				}
				this.Timeshow = true
			},
			// pda扫码
			scanHandler(scanData) {
				let that = this;

				that.MoludChange(scanData.recode, 'pda')
			},
			// 手机扫描
			scan() {
				let that = this;

				this.$scanPopup.openScan({
					success: function(res) {

						that.MoludChange(res.result, 'phone')
					},
					fail: function(fail) {
						console.log(fail);
					}
				})

			},
			// 处理扫码数据
			MoludChange(res, name) {
				let that = this;
				let parts = res.split("|");
				var id = parts[1]
				var obj = {}
				if (parts[0] == 'MJ') {
					obj.MoludID = id
				} else if (parts[0] == 'MJKW') {
					obj.FStorageID = id
				}
				console.log(obj);
				that.Request.request('MJ_MoludList', obj, (ret) => {
					console.log(ret);
					if (ret.data.ds1[0].status == 500) {
						uni.$u.toast(ret.data.ds1[0].msg)
					} else {
						ret.data.ds.map(obj => {
							obj.WarningStatus = obj.WarningStatus ? obj.WarningStatus : 0
							obj.WarningStatusName = obj.WarningStatusName ? obj.WarningStatusName : ''
							obj.StockDeID = obj.StockDeID ? obj.StockDeID : 0
						})
						that.tableData = [...that.tableData, ...ret.data.ds]
					}
				})
			},


			openBaseScreen(str, type, index) { // 前往筛选页
				let that = this;
				let obj = null;
				let url = null;
				switch (type) {
					case 'radio': // 单选项
						url = '/commonPage/Tool/baseScreen';
						if (str == '库位') {
							that.BaseScreenIndex = index
							obj = {
								allowClear: false,
								cmd: 'MJ_StorageList',
								type: str,
								ListeningName: 'st_mold_Choice',
								serverSearch: {
									isPaging: false, //是否分页
									searchKey: 'FStorageName', //搜索关键词，应包含在param中
									showText: 'FStorageName', //查询结果显示的字段
									pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								},
								param: {

									FStorageName: '',
									PageIndex: 1,
									PageSize: 30
								}
							}
						}

						break;
					case 'check': // 多选
						url = '/commonPage/Tool/SelectBaseScreen';

						if (str == '模具') {
							obj = {
								allowClear: false,
								cmd: 'MJ_MoludList',
								type: str,
								ListeningName: 'st_mold_Choice',
								serverSearch: {
									isPaging: false, //是否分页
									searchKey: 'MoludSelect', //搜索关键词，应包含在param中
									showText: 'MoludSelect', //查询结果显示的字段
									pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
									// ChoiceDataKey: 'MoludName',
									// ChoiceDataData: that.baseFormData.MoludName,
								},
								param: {
									FType: that.WorkbenchesTitle == '领用' ? 'LY' : 'GH',
									IsInStorage: that.WorkbenchesTitle == '领用' ? 1 : 0,
									MoludSelect: '',
									PageIndex: 1,
									PageSize: 30
								}
							}
						}
						break;
					default:
						break;
				}


				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})
				uni.navigateTo({
					url: url
				})


			},

			// 审核/取消审核
			ToExamine(str) {
				if (str == '取消审核') {
					this.SJJ_ApproveChange(str, this.baseFormData.StockID)
				} else {
					this.SubmitBtn(str)
				}
			},
			// 审核
			SJJ_ApproveChange(str, StockID) {
				let that = this;

				var msg
				var Motion
				if (str == '审核') {
					Motion = 1
					msg = '审核成功'
				} else {
					Motion = -1
					msg = '撤审成功'
				}
				var obj1 = {
					StockID: StockID,
					Motion: Motion,
					FType: that.WorkbenchesTitle == '领用' ? 'LY' : 'GH',
				}
				console.log(obj1);

				that.Request.request('MJ_LYGHApprove', obj1, function(res) {
					if (res.data.ds[0].status == 500) {
						uni.$u.toast(res.data.ds[0].msg)
						that.queryList(StockID);
					} else {

						that.$refs.uToast.show({
							title: '保存',
							type: 'success',
							message: msg
						})
						that.queryList(StockID);
					}

				}, function(err) {
					console.log(err)
				})
			},
			// 提交按钮
			SubmitBtn(str) {
				let that = this;
				var show = true
				var msg
				if (that.tableData.length == 0) {
					show = false
					msg = '请新增模具'
				}
				if (show) {
					this.$refs.uForm.validate().then(res => {
						var FType
						let obj = {
							BillDate: that.baseFormData.BillDate,
							EmplID: that.baseFormData.EmplID,
							BillDate: that.baseFormData.BillDate,
							StockID: that.baseFormData.StockID,
							MoludID: that.tableData.map(item => item.MoludID).join(','),
							StockDeID: that.tableData.map(item => item.StockDeID).join(','),
							FStorageID: that.tableData.map(item => item.FStorageID).join(','),
						};
						if (that.WorkbenchesTitle == '领用') {
							obj.FType = 'LY'
							obj.CKTime = that.baseFormData.CKTime
						} else {
							obj.FType = 'GH'
							obj.RKTime = that.baseFormData.RKTime
						}
						console.log(obj)
						that.Request.request('MJ_LYSubmit', obj, function(ret) {
							console.log(ret)
							var StockID = ret.data.ds[0].StockID
							if (ret.data.ds[0].status == 500) {
								uni.$u.toast(ret.data.ds[0].msg)
							} else {
								if (str == '保存') {
									that.$refs.uToast.show({
										title: '保存',
										type: 'success',
										message: '保存成功'
									})
									that.queryList(StockID);
								} else {
									that.SJJ_ApproveChange(str, StockID)
								}
							}
						}, function(err) {
							console.log(err)
						})
					}).catch(errors => {
						console.log(JSON.stringify(errors))
						if (Array.isArray(errors)) {
							uni.$u.toast('请完善表单')
						}
					});
				} else {
					that.modaltitle = '提醒'
					that.modalcontent = msg
					that.modalshow = true
				}

			},

			// 详情
			queryList(id) {
				var that = this
				that.loading = true
				try {
					that.Request.request('MJ_LYDetail', {
						StockID: id
					}, (ret) => {
						console.log(ret.data);
						that.loading = false
						ret.data.ds.map((item) => {
							item.CKTime = formatDateTime(item.CKTime)
							item.BillDate = formatDateTime(item.BillDate)
							item.RKTime = formatDateTime(item.RKTime)

						})
						ret.data.ds1.map((item) => {
							item.WarningStatus = item.WarningStatus ? item.WarningStatus : 0
							const dictMappings = {
								WarningStatus: {
									dictKey: 'LYGHWS',
									targetField: 'WarningStatusName'
								}
							};
							that.mapDictNamesForItem(item, dictMappings);
						})
						that.baseFormData = ret.data.ds[0]
						console.log(ret.data.ds1);
						that.tableData = ret.data.ds1
						that.$forceUpdate()

					})
				} catch (e) {
					that.loading = false
					console.log(e)

					this.$utils.msg('请求失败请重试')
				}
			},
			// 退出
			leftClick() {
				let routes = getCurrentPages(); //当前页面栈
				let prevPage = routes[routes.length - 2]
				if (prevPage && prevPage.$vm && typeof prevPage.$vm.getList === 'function') {
					prevPage.$vm.getList()
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/index.scss";

	.active-row-yellow td text {
		color: red;
	}

	.fixed-cell {
		white-space: normal;
		word-wrap: break-word;
		word-break: break-all;
	}

	.text-red {
		color: red !important;

		.fixed-cell {
			color: red !important;

		}
	}

	.Main_CardListBox {
		padding: 0px;
	}

	.content {
		.BottomBox {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding: 10px 10px;

			.CancelBtn {
				background-color: #fff;
				color: #51d0d0;
				border: 1px solid #51d0d0;
				min-width: 80px;
			}

			.ComfirmBtn {
				background-color: #51d0d0;
				color: #fff;
				min-width: 80px;
				margin-left: 10px !important;
			}
		}
	}



	.uni-table-tr:hover,
	.uni-table-tr:active,
	.uni-table-tr.hover {
		background-color: transparent !important;
	}


	.uni-td {
		-webkit-tap-highlight-color: transparent;
		/* 移除点击高亮 */
	}


	.uni-tr--hover {
		background-color: transparent !important;
	}

	.AddBottomBox {
		justify-content: flex-end;
	}
</style>